package Filters;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(value = "/*", initParams = {@WebInitParam(name = "encoding", value = "UTF-8"), @WebInitParam(name = "content", value = "text/html;charset=UTF-8")})
public class EncodeFilter implements Filter {
    private String encoding;
    private String content;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
        content = filterConfig.getInitParameter("content");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {

        String ip = req.getRemoteAddr();
        //log.info("ip: " + ip);
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Headers", "Content-Type");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Methods", "GET,POST");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", "*");
        HttpServletRequest request = (HttpServletRequest) req;
        req.setCharacterEncoding(encoding);
        res.setCharacterEncoding(encoding);
        String URI = request.getRequestURI();
        if (URI.contains(".pdf") || URI.contains(".png") || URI.contains(".jpg") || URI.contains(".jpeg") || URI.contains(".html") || URI.contains(".css") || URI.contains(".js") || URI.contains(".doc") || URI.contains(".docx") || URI.contains(".ppt")) {
        } else {
            res.setContentType(content);
        }
        filterChain.doFilter(req, res);
    }

    @Override
    public void destroy() {
    }
}
